package com.xf.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.CaseFormat;
import com.xf.common.core.domain.DmpResult;
import com.xf.common.core.entity.constant.StringConstant;
import com.xf.common.core.entity.dmp.DmpAuthUser;
import com.xf.common.core.entity.system.DmpUserAssignDto;
import com.xf.common.core.entity.system.SystemUser;
import com.xf.common.core.exception.FebsException;
import com.xf.common.core.page.PageBuilder;
import com.xf.common.core.page.PageQuery;
import com.xf.common.core.utils.FebsUtil;
import com.xf.service.DmpAuthUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.*;

//import com.xf.service.IUserService;

/**
 * @author MrBird
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("user")
public class UserController {

    private final DmpAuthUserService userService;

    private final PasswordEncoder passwordEncoder;

    @GetMapping("index")
    public DmpResult index() {
        Map<String, Object> data = new HashMap<>(5);
        // 获取系统访问记录
        data.put("totalVisitCount", 1);
        data.put("todayVisitCount", 1);
        data.put("todayIp", 1);
        // 获取近期系统访问记录
        List<Map<String, Object>> lastTenVisitCount = new ArrayList<>();
        data.put("lastTenVisitCount", lastTenVisitCount);
        DmpAuthUser param = new DmpAuthUser();
        param.setUserName(FebsUtil.getCurrentUsername());
        List<Map<String, Object>> lastTenUserVisitCount = new ArrayList<>();
        data.put("lastTenUserVisitCount", lastTenUserVisitCount);
        return DmpResult.data(data);
    }

    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "aliasOrName", value = "用户昵称或帐号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "用户状态", paramType = "query", dataType = "Integer")
    })
    @GetMapping(value = "/getPage")
    public DmpResult<IPage<SystemUser>> getListByPage(PageQuery pageQuery, String aliasOrName, Integer state) {
        if (Objects.nonNull(pageQuery.getAscs())) {
            pageQuery.setAscs(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, pageQuery.getAscs()));
        }
        if (Objects.nonNull(pageQuery.getDescs())) {
            pageQuery.setDescs(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, pageQuery.getDescs()));
        }
        IPage<SystemUser> page = PageBuilder.build(pageQuery);
        return DmpResult.data(userService.page(page, aliasOrName, state));
    }

    @ApiOperation("检查用户名是否存在")
    @GetMapping("check/{username}")
    public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username) {
        return this.userService.findByName(username) == null;
    }

    @ApiOperation("添加用户")
    @PostMapping("/add")
    public DmpResult addUser(@Valid @RequestBody DmpAuthUser user) {
        this.userService.createUser(user);
        return DmpResult.success();
    }

    @ApiOperation("修改用户")
    @PutMapping("update")
    public void updateUser(@Valid @RequestBody DmpAuthUser user) {
        this.userService.updateUser(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{userIds}")
    public void deleteUsers(@NotBlank(message = "{required}") @PathVariable String userIds) {
        String[] ids = userIds.split(StringConstant.COMMA);
        this.userService.deleteUsers(ids);
    }


    @ApiOperation("用户分配角色和用户组")
    @PostMapping(value = "/assign")
    public DmpResult assign(@RequestBody DmpUserAssignDto dmpUserAssignDto) {
        return userService.assign(dmpUserAssignDto);
    }

    @ApiOperation("更新个人信息")
    @PutMapping("updateProfile")
    public void updateProfile(@Valid @RequestBody DmpAuthUser user) throws FebsException {
        this.userService.updateProfile(user);
    }


    @ApiOperation("更新用户头像")
    @PutMapping("updateAvatar")
    public void updateAvatar(@NotBlank(message = "{required}") String avatar) {
        this.userService.updateAvatar(avatar);
    }

//    @GetMapping("password/check")
//    public boolean checkPassword(@NotBlank(message = "{required}") String password) {
//        String currentUsername = FebsUtil.getCurrentUsername();
//        DmpAuthUser user = userService.findByName(currentUsername);
//        return user != null && passwordEncoder.matches(password, user.getPassword());
//    }

    @ApiOperation("更新用户密码")
    @PutMapping("password")
    public void updatePassword(@NotBlank(message = "{required}") String password) {

        userService.updatePassword(passwordEncoder.encode(password));
    }

    @ApiOperation("用户重置密码")
    @PutMapping("password/reset")
    public void resetPassword(@NotBlank(message = "{required}") String usernames) {
        String[] usernameArr = usernames.split(StringConstant.COMMA);
        this.userService.resetPassword(usernameArr);
    }

}
